package com.ruoyi.operation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.mybatis.core.page.PageQuery;
import com.ruoyi.common.mybatis.core.page.TableDataInfo;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.ruoyi.operation.domain.bo.TBusisystemBo;
import com.ruoyi.operation.domain.vo.TBusisystemVo;
import com.ruoyi.operation.domain.TBusisystem;
import com.ruoyi.operation.mapper.TBusisystemMapper;
import com.ruoyi.operation.service.ITBusisystemService;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 业务系统，从CMDB同步Service业务层处理
 *
 * @author chq
 * @date 2025-06-13
 */
@RequiredArgsConstructor
@Service
@Slf4j
public class TBusisystemServiceImpl implements ITBusisystemService {

    private final TBusisystemMapper baseMapper;

    /**
     * 查询业务系统，从CMDB同步
     */
    @Override
    public TBusisystemVo queryById(String id){
        return baseMapper.selectVoById(id);
    }

    /**
     * 查询业务系统，从CMDB同步列表
     */
    @Override
    public TableDataInfo<TBusisystemVo> queryPageList(TBusisystemBo bo, PageQuery pageQuery) {
        LambdaQueryWrapper<TBusisystem> lqw = buildQueryWrapper(bo);
        Page<TBusisystemVo> result = baseMapper.selectVoPage(pageQuery.build(), lqw);
        return TableDataInfo.build(result);
    }

    /**
     * 查询业务系统，从CMDB同步列表
     */
    @Override
    public List<TBusisystemVo> queryList(TBusisystemBo bo) {
        LambdaQueryWrapper<TBusisystem> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<TBusisystem> buildQueryWrapper(TBusisystemBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<TBusisystem> lqw = Wrappers.lambdaQuery();
        lqw.eq(StringUtils.isNotBlank(bo.getCmdbid()), TBusisystem::getCmdbid, bo.getCmdbid());
        lqw.like(StringUtils.isNotBlank(bo.getName()), TBusisystem::getName, bo.getName());
        return lqw;
    }

    /**
     * 新增业务系统，从CMDB同步
     */
    @Override
    public Boolean insertByBo(TBusisystemBo bo) {
        TBusisystem add = BeanUtil.toBean(bo, TBusisystem.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setId(add.getId());
        }
        return flag;
    }

    /**
     * 修改业务系统，从CMDB同步
     */
    @Override
    public Boolean updateByBo(TBusisystemBo bo) {
        TBusisystem update = BeanUtil.toBean(bo, TBusisystem.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(TBusisystem entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除业务系统，从CMDB同步
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<String> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public Boolean currentCMDB(List<Map<String, String>> resultData) {
        if (CollUtil.isEmpty(resultData)) {
            log.info("没有数据需要同步");
            return false;
        }
        List<String> existBusiId = baseMapper
            .selectList()
            .stream()
            .map(TBusisystem::getCmdbid)
            .collect(Collectors.toList());
        log.info("拿到的存量cmdbid{}",existBusiId);
        List<TBusisystem> tBusisystemList = resultData.stream().filter(obj ->{
            log.info("当前同步数据为{}",obj);
            log.info("获取到的id为:{}",obj.get("ID"));
            log.info("{}",existBusiId.contains(String.valueOf(obj.get("ID"))));
            return !existBusiId.contains(String.valueOf(obj.get("ID")));
        }).map(obj -> {
            log.info("当前同步数据为{}",obj);
            TBusisystem busisystem = new TBusisystem();
            busisystem.setCreateBy("Dolphin");
            busisystem.setUpdateBy("Dolphin");
            busisystem.setCreateTime(new Date());
            busisystem.setCmdbid(String.valueOf(obj.get("ID")));
            busisystem.setName(String.valueOf(obj.get("name")));
            return busisystem;
        }).collect(Collectors.toList());
        log.info("需要保存的数据为{}",tBusisystemList);
        return baseMapper.insertOrUpdateBatch(tBusisystemList);
    }
}
